package com.vote.dao;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.vote.dao.util.HibernateDao;
import com.vote.dao.util.Page;
import com.vote.entity.Respondent;

@Repository
public class RespondentDao extends HibernateDao<Respondent, Long> {
	
	private static Logger log = LoggerFactory.getLogger(RespondentDao.class);
	
	public Page<Respondent> listByPage(Page<Respondent> page, DetachedCriteria detach) {
		return this.findPage(page, detach);
	}		
	public Boolean saveResp(Respondent resp){
		Boolean flag= false;
		Long cnt=null;
		if(StringUtils.isNotEmpty(resp.getIp()) && StringUtils.isNotEmpty(resp.getCookie())){
			cnt=this.countHqlResult(" from Respondent r where r.ip=? and r.cookie=?",resp.getIp(),resp.getCookie());
		}		
		if(cnt>0){
			flag=true;
		}else{
			this.save(resp);
		}
		return flag;		
	}
	
	public Respondent findRespondentByIpOrCookie(String ip,String cookie){
		String hql=" from Respondent r where r.ip=? and r.cookie=?";		
		List<Respondent> respLst= this.createQuery(hql, ip,cookie).list();
		if(respLst!=null && !respLst.isEmpty()){
			return respLst.get(0);
		}else{
			return null;
		}
		
	}
}